<template>
  <div>
    <el-breadcrumb separator="/">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>分类参数</el-breadcrumb-item>
    </el-breadcrumb>
    <el-card style="margin-top:20px;">
      <el-alert show-icon title="注意：只允许为第三级分类设置相关参数！" type="warning"></el-alert>
      <el-row style="margin-top:20px">
        <el-col>
          <span>添加分类:</span>
          <el-cascader
            v-model="selectKeys"
            :props="cateProps"
            :options="cateList"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>
      <!-- 标签页 -->

      <el-tabs v-show="isTabs" v-model="activeName" @tab-click="handleClick">
        <el-tab-pane label="静态参数" name="only">
          <el-button type="success" size="mini" @click="manyAdd">添加属性</el-button>
          <el-table :data="onlyList" border style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  style="margin:10px;"
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="tagClose(scope.row,index)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  v-show="scope.row.attr_vals.length===0"
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称" width="180"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="warning"
                  size="mini"
                  class="el-icon-edit"
                  @click="manyEdite(scope.row)"
                >修改</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  class="el-icon-delete"
                  @click="manyDel(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="动态参数" name="many">
          <el-button type="success" size="mini" @click="manyAdd">增加参数</el-button>
          <el-table :data="manyList" border style="width: 100%">
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  style="margin:10px;"
                  v-for="(item,index) in scope.row.attr_vals"
                  :key="index"
                  closable
                  @close="tagClose(scope.row,index)"
                >{{item}}</el-tag>
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible"
                  v-model="scope.row.inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                ></el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                >+ New Tag</el-button>
              </template>
            </el-table-column>
            <el-table-column prop="attr_name" label="参数名称" width="180"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="warning"
                  size="mini"
                  class="el-icon-edit"
                  @click="manyEdite(scope.row)"
                >修改</el-button>
                <el-button
                  type="danger"
                  size="mini"
                  class="el-icon-delete"
                  @click="manyDel(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>
    <!-- 添加参数对话框 -->
    <el-dialog :title="titleText" :visible.sync="addDialogVisible" width="50%" @close="addClose">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addMethod">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 修改参数对话框 -->
    <el-dialog :title="titleText" :visible.sync="ediDialogVisible" width="50%" @close="ediClose">
      <el-form :model="ediForm" :rules="ediFormRules" ref="ediFormRef" label-width="100px">
        <el-form-item :label="titleText" prop="attr_name">
          <el-input v-model="ediForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="ediDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="ediMethod">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
export default {
  data() {
    return {
      // 级联选择器绑定数据
      selectKeys: [],
      // 类别数据
      cateList: [],
      // 级联选择器配置对象
      cateProps: {
        label: "cat_name",
        value: "cat_id",
        children: "children"
      },
      // 标签页指定name  默认only
      activeName: "only",
      // 设置标签页默认不展示
      isTabs: false,
      // many 数据
      manyList: [],
      // only 数据
      onlyList: [],
      // 添加一系列
      addForm: {
        attr_name: ""
      },
      addDialogVisible: false,
      addFormRules: {
        attr_name: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" }
        ]
      },
      // 修改一系列
      ediDialogVisible: false,
      ediForm: {
        attr_name: ""
      },
      ediFormRules: {
        attr_name: [
          { required: true, message: "请输入角色名称", trigger: "blur" },
          { min: 2, max: 8, message: "长度在 2 到 8 个字符", trigger: "blur" }
        ]
      }
    };
  },
  methods: {
    // 获取类别数据  获取全部
    async getCateList() {
      const { data: res } = await this.$http.get("categories");
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.cateList = res.data;
      // console.log(res.data);
    },
    // 级联选择器发生改变时
    handleChange() {
      // 发送数据获取请求
      this.getParamsList();
    },
    // 标签页发生改变时,执行事件
    async handleClick() {
      this.getParamsList();
    },
    // 获取参数事件
    async getParamsList() {
      let id = this.selectKeys[2];
      if (this.selectKeys.length !== 3) {
        this.isTabs = false;
        return;
      }
      // 发送请求 根据activeName获取数据
      const { data: res } = await this.$http.get(
        `categories/${id}/attributes`,
        { params: { sel: this.activeName } }
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      res.data.forEach(element => {
        element.attr_vals = element.attr_vals
          ? this.activeName === "only"
            ? element.attr_vals.split("|转数组")
            : element.attr_vals.split(" ")
          : [];
        element.inputVisible = false;
        element.inputValue = "";
      });
      // console.log(res.data);
      if (this.activeName === "many") {
        this.manyList = res.data;
      } else {
        this.onlyList = res.data;
      }
      this.isTabs = true;
    },
    // 增加事件
    async manyAdd() {
      this.addDialogVisible = true;
    },
    // 增加对话框关闭事件
    addClose() {
      this.$refs.addFormRef.resetFields();
    },
    // 增加确认事件
    addMethod() {
      let id = this.selectKeys[2];
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;
        const { data: res } = await this.$http.post(
          `categories/${id}/attributes`,
          {
            attr_name: this.addForm.attr_name,
            attr_sel: this.activeName
          }
        );
        if (res.meta.status !== 201) return this.$message.error(res.meta.msg);
        this.getParamsList();
        this.$message.success(res.meta.msg);
        this.addDialogVisible = false;
      });
    },
    // 修改事件
    async manyEdite(row) {
      let id = this.selectKeys[2];
      const { data: res } = await this.$http.get(
        `categories/${id}/attributes/${row.attr_id}`,
        {
          params: {
            attr_sel: this.activeName
          }
        }
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.ediForm = res.data;
      this.ediDialogVisible = true;
    },
    // 修改对话框关闭事件
    ediClose() {
      this.$refs.ediFormRef.resetFields();
    },
    // 修改确认事件
    async ediMethod() {
      this.$refs.ediFormRef.validate(async valid => {
        if (!valid) return;
        let id = this.selectKeys[2];
        const { data: res } = await this.$http.put(
          `categories/${id}/attributes/${this.ediForm.attr_id}`,
          {
            attr_sel: this.activeName,
            attr_name: this.ediForm.attr_name,
            attr_vals: this.ediForm.attr_vals
          }
        );
        if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
        this.getParamsList();
        this.$message.success(res.meta.msg);
        this.ediDialogVisible = false;
      });
    },
    // 删除事件
    async manyDel(info) {
      let id = this.selectKeys[2];
      let del = await this.$confirm(
        `此操作将永久删除该${info.attr_name}, 是否继续?`,
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }
      ).catch(err => err);
      if (del !== "confirm") return this.$message.info("取消了删除");
      const { data: res } = await this.$http.delete(
        `categories/${id}/attributes/${info.attr_id}`
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      this.getParamsList();
    },
    // 删除标签事件
    async tagClose(row, index) {
      // console.log(row.attr_vals);
      row.attr_vals.splice(index, 1);
      let id = this.selectKeys[2];
      const { data: res } = await this.$http.put(
        `categories/${id}/attributes/${row.attr_id}`,
        {
          attr_sel: this.activeName,
          attr_name: row.attr_name,
          attr_vals: row.attr_vals.join(" ")
        }
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
    },
    // 点击tag事件
    showInput(row) {
      row.inputVisible = true;
      this.$nextTick(_ => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },
    // tag增加事件
    async handleInputConfirm(row) {
      if (row.inputValue.trim().length === 0) {
        row.inputVisible = false;
        return;
      }
      row.attr_vals.push(row.inputValue);
      let id = this.selectKeys[2];
      const { data: res } = await this.$http.put(
        `categories/${id}/attributes/${row.attr_id}`,
        {
          attr_sel: this.activeName,
          attr_name: row.attr_name,
          attr_vals: row.attr_vals.join(" ")
        }
      );
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.$message.success(res.meta.msg);
      row.inputVisible = false;
      row.inputValue = "";
    }
  },
  created() {
    this.getCateList();
  },
  computed: {
    titleText() {
      if (this.activeName === "many") return "动态参数";
      return "静态属性";
    }
  }
};
</script>
<style lang="less" scoped>
.input-new-tag {
  width: 130px;
}
</style>